<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 ,一行是24个宽度-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
      <el-table :data="userlist" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="username" label="姓名"></el-table-column>
            <el-table-column prop="nickname" label="权限模板名称"></el-table-column>
            <el-table-column label="状态">
              <!-- 在状态这一列，通过作用域插槽，接受了scope，就可以通过scope点出来row这个属性，就代表这一行的数据 -->
              <template slot-scope="scope">
                <el-switch v-model="scope.row.is_active" @change="userStateChanged(scope.row)">
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="idle_time" label="过期时间"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column label="操作" width="180px">
              <!-- 通过作用域插槽来进行操作的自我定义 -->
              <template slot-scope="scope">
                  <!-- 修改按钮 -->
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.username)"></el-button>
                  <!-- 删除按钮 -->
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByUsername(scope.row.username)"></el-button>
                  <!-- 角色分配按钮 -->
                  <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                        <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
                  </el-tooltip>
              </template>
            </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="queryInfo.page"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.rows"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="创建用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="110px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="模板名" prop="nickname">
          <el-input v-model="addForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="description">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="per_name">
          <el-input v-model="addForm.per_name"></el-input>
        </el-form-item>
        <el-form-item label="过期时间" prop="idle_time">
          <el-input v-model="addForm.idle_time"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="is_active">
          <el-switch v-model="addForm.is_active"></el-switch>
        </el-form-item>
        <el-form-item label="账号锁定时间" prop="lock_time">
          <el-input v-model="addForm.lock_time"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @closed="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="110px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="模板名" prop="nickname">
          <el-input v-model="editForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="per_name">
          <el-input v-model="editForm.per_name"></el-input>
        </el-form-item>
        <el-form-item label="过期时间" prop="idle_time">
          <el-input v-model="editForm.idle_time"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="is_active">
          <el-switch v-model="editForm.is_active"></el-switch>
        </el-form-item>
        <el-form-item label="账号锁定时间" prop="lock_time">
          <el-input v-model="editForm.lock_time"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义验证邮箱的规则,value是需要校验的值,还有一个是回调函数
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmail.test(value)){
        // 这是合法的邮箱
        return cb()
      }
      cb(new Error("请输入合法的邮箱"))
    }
    // 自定义验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if(regMobile.test(value)){
        // 这是合法的手机号
        return cb()
      }
      cb(new Error("请输入合法的手机号"))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        // 搜索的内容
        query: "",
        // 当前的页数
        page: 1,
        // 当前每页显示多少条数据
        rows: 5
      },
      userlist: [],
      total: 0,
      putForm: {
        username: "",
        nickname: "",
        idle_time: "",
        lock_time: "",
        description: "",
        password: "",
        is_active: false,
        per_name: ""
      },
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: "",
        nickname: "",
        idle_time: "",
        lock_time: "",
        description: "",
        password: "",
        is_active: false,
        per_name: ""
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {min: 3, max:10, message: "用户名的长度在3到10个字符之间", trigger: "blur"}
        ],
        nickname: [
          {required: true, message: "请输入模板名称", trigger: "blur"},
          {min: 3, max:10, message: "模板名的长度在3到15个字符之间", trigger: "blur"}
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {min: 6, max:10, message: "密码的长度在6到15个字符之间", trigger: "blur"}
        ],
        description: [
          {required: false, message: "请输入邮箱信息", trigger: "blur"},
          {min: 6, max:20, message: "邮箱的长度在6到20个字符之间", trigger: "blur"},
          {validator: checkEmail, trigger: "blur"}
        ],
        per_name: [
          {required: false, message: "请输入手机号信息", trigger: "blur"},
          {min: 6, max:20, message: "手机号的长度在6到20个字符之间", trigger: "blur"},
          {validator: checkMobile, trigger: "blur"}
        ],
        idle_time: [
          {required: true, message: "请输入超时时间", trigger: "blur"}
        ],
        is_active: [
          {required: false, message: "是否启用按钮", trigger: "blur"}
        ],
        lock_time: [
          {required: true, message: "账号锁定时间", trigger: "blur"}
        ]
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "blur"},
          {min: 3, max:10, message: "用户名的长度在3到10个字符之间", trigger: "blur"}
        ],
        nickname: [
          {required: true, message: "请输入模板名称", trigger: "blur"},
          {min: 3, max:10, message: "模板名的长度在3到15个字符之间", trigger: "blur"}
        ],
        description: [
          {required: false, message: "请输入邮箱信息", trigger: "blur"},
          {min: 6, max:20, message: "邮箱的长度在6到20个字符之间", trigger: "blur"},
          {validator: checkEmail, trigger: "blur"}
        ],
        per_name: [
          {required: false, message: "请输入手机号信息", trigger: "blur"},
          {min: 6, max:20, message: "手机号的长度在6到20个字符之间", trigger: "blur"},
          {validator: checkMobile, trigger: "blur"}
        ],
        idle_time: [
          {required: true, message: "请输入超时时间", trigger: "blur"}
        ],
        is_active: [
          {required: false, message: "是否启用按钮", trigger: "blur"}
        ],
        lock_time: [
          {required: true, message: "账号锁定时间", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    // 需要在这里面发起请求获取列表的数据
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('v1/system/user', { params: this.queryInfo })
      if(res.status !== 0) {
        return this.$message.error("获取用户列表失败")
      }
      this.userlist = res.data.rows
      this.total = res.data.total
    },
    // 监听pagesize改变的事件,可以拿到最新的pagesize
    handleSizeChange(newsize) {
      // 如果发生人为输入变化了就需要重新发起请求获取这一页的数据
      this.queryInfo.rows = newsize
      this.getUserList()
    },
    // 监听页码值改变的事件，可以拿到最新的页码值
    handleCurrentChange(newpage) {
      // 如果发生人为输入变化了就需要重新发起请求获取这一页的数据
      this.queryInfo.page = newpage
      this.getUserList()
    },
    // 监听switch开关状态的改变
    async userStateChanged(userinfo){
      this.putForm.username = userinfo.username
      this.putForm.nickname = userinfo.nickname
      this.putForm.idle_time = userinfo.idle_time
      this.putForm.lock_time = userinfo.lock_time
      this.putForm.description = userinfo.description
      this.putForm.password = userinfo.password
      this.putForm.is_active = userinfo.is_active
      this.putForm.per_name = userinfo.per_name
      const {data:res} = await this.$http.put("v1/system/user", this.putForm)
      if(res.status !== 0){
        userinfo.is_active = !userinfo.is_active
        return this.$message.error("更新用户状态失败")
      }
      this.$message.success("更新用户状态成功")
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        // 这个valid是接受校验结果的
        if(!valid) return
        // 如果valid是true就代表验证通过了，可发起网络请求了
        this.addForm.password = this.Base64.encode(this.addForm.password)
        console.log(this.addForm)
        const {data: res} = await this.$http.post("v1/system/user", this.addForm)
        if(res.status !== 0){
          return this.$message.error("添加用户失败")
        }
        this.$message.success("添加用户成功")
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表的数据
        this.getUserList()
      })
    },
    // 展示用户编辑页面的对话框
    async showEditDialog(username){
      // console.log(username)
      const {data: res} = await this.$http.get('v1/system/user/' + username)
      if(res.status !== 0){
        return this.$message.error("查询用户信息失败")
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改用户对话框的关闭事件,应用的作用就是引用整个表单，重置所有的验证的结果
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) return
        // 发起修改用户信息的数据请求
        const {data: res} = await this.$http.put("v1/system/user", this.editForm)
        if(res.status !== 0) {
          return this.$message.error("更新用户信息失败")
        }
        // 成功后关闭对话框
        this.editDialogVisible = false
        // 刷新用户列表
        this.getUserList()
        // 提示修改成功
        this.$message.success("更新用户信息成功")
      })
    },
    // 按照用户名删除对应的用户
    async removeUserByUsername(username) {
      console.log(username)
      // 不能直接删除，要先询问用户是否删除数据，这个confirm的返回值是promise，可以用async和await进行优化了,如果用户确认删除，
      // 则返回值为字符串confirm，如果点击取消则会触发$confirm中的一个错误,接受一个错误return出去就是打印了cancel，然后进行判断用户是否真的删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      console.log(confirmResult)
      if(confirmResult !== "confirm") {
        return this.$message.info("已经取消删除")
      }
      const {data: res} = await this.$http.delete("v1/system/user/" + username)
      console.log(res)
      if(res.status !== 0){
        return this.$message.error("删除用户失败")
      }
      this.$message.success("删除用户成功")
      // 成功后刷新一下用户列表
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
